package cn.edu.zzuli.web.dao;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.springframework.stereotype.Repository;
import org.wltea.analyzer.lucene.IKAnalyzer;

import cn.edu.zzuli.web.bean.Forum;
import cn.edu.zzuli.web.bean.rowmapper.IndexRowMapper;
import cn.edu.zzuli.web.dao.base.AbstractDao;

/**
 * 
 * 类名称：CreateIndex 类描述： 创建索引的工具类 创建时间：May 28, 2011 10:46:59 AM 修改人： 修改时间：May 28,
 * 2011 10:46:59 AM 修改备注：
 * 
 * @version
 */
@Repository("createIndex")
public class CreateIndex extends AbstractDao {

	String indexPath = "d:\\index1";
	
	/**
	 * 创建索引
	 * 
	 * @Title: create
	 * @Description:
	 */
	public void create() {
		IndexWriter iwriter = null;
		Directory directory = null;
		Analyzer analyzer = new IKAnalyzer();
		String sql = "SELECT id,title,content  FROM Forum ";
		try {
			List<Forum> list = this.getJdbcTemplate().query(sql, new IndexRowMapper());
			// 建立索引开始
			File file = new File(indexPath);
			if (!file.exists())
				file.createNewFile();
			directory = FSDirectory.open(file);

			iwriter = new IndexWriter(directory, analyzer, true,IndexWriter.MaxFieldLength.LIMITED);
			Document doc = null;
			int id = 0;
			String title = "";
			String content = "";
			for(Forum f : list){
				doc = new Document();
				id = f.getId();
				if(f.getTitle()!=null)
					title = f.getTitle();
				content = f.getContent();
				doc.add(new Field("id", "" + id, Field.Store.YES,
						Field.Index.ANALYZED));
				doc.add(new Field("title", title, Field.Store.YES,
						Field.Index.ANALYZED));
				doc.add(new Field("content", content, Field.Store.YES,
						Field.Index.ANALYZED));
				iwriter.addDocument(doc);
			}
			// 建立索引结束
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (iwriter != null) {
				try {
					iwriter.close();
				} catch (CorruptIndexException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static void main(String[] args) {
		new CreateIndex().create();
		System.out.println("KO");
	}
}
